import { checkHttpStatus, parseJSON } from '../utils';
import { REG_USER_REQUEST, REG_USER_SUCCESS, REG_USER_FAILURE } from '../contants/index';
import { browserHistory } from 'react-router'


export function regUserSuccess(session) {
   localStorage.setItem('session', session);
   console.log(session);
  return {
    type: REG_USER_SUCCESS,
    payload: {
      session: session
    }
  }
}

export function regUserFailure(error) {
  localStorage.removeItem('session');
  return {
    type: REG_USER_FAILURE,
    payload: {
      errContent: error.content,
      errCode: error.code
    }
  }
}

export function regUserRequest() {
  return {
    type: REG_USER_REQUEST
  }
}

export function regUser(userPhone,userPass,userName,userEmail,ValidateCode) {
    return function(dispatch) {
        dispatch(regUserRequest());
        return fetch("http://fengke.net:8081/web/reg", {
            method: 'POST',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
        },
            body: JSON.stringify({
                userPhone: userPhone,
                userPass: userPass,
                ValidateCode: ValidateCode,
                userName: userName,
                userEmail: userEmail
        })
})
   .then(checkHttpStatus)
   .then(parseJSON)
   .then(
        response => {
                console.log("response");
                console.log(response);
                if(response.status=="1"){
                dispatch(regUserSuccess(response.data.userId));
                }else{
                dispatch(regUserFailure(response.errmsg));
                }
    },
        error =>{
                dispatch(regUserFailure(response.errmsg));
    })

}
}